package com.smile.frame.alibaba.services.gateway.config;


import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.ratelimit.KeyResolver;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import reactor.core.publisher.Mono;

import java.util.Objects;


/**
 * 限流配置
 *
 * @author LGC
 */
@Slf4j
@Configuration
public class RateLimiterConfig {

    /**
     * 按IP来限流
     */
    @Bean
    @Primary
    KeyResolver ipKeyResolver() {
        return exchange -> Mono.just(Objects.requireNonNull(exchange.getRequest().getRemoteAddress()).getHostName());
    }

    /**
     * 按URL限流,即以每秒内请求数按URL分组统计，超出限流的url请求都将返回429状态
     */
    @Bean
    KeyResolver apiKeyResolver() {

        return exchange -> Mono.just(exchange.getRequest().getPath().toString());
    }

    /**
     * 按用户限流
     */
    @Bean
    KeyResolver userKeyResolver() {
        return exchange -> Mono.just(Objects.requireNonNull(exchange.getRequest().getHeaders().getFirst("thoen")));
    }


}
